package hamaster.jpbc.pbc;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;

public final class PBCDriver {

	public static String hex(byte[] data) {
		return hex(data, 0, data.length);
	}

	public static String hex(byte[] data, int offset, int count) {
		if (offset < 0)
			throw new IllegalArgumentException("invalid offset:" + offset);
        if (count < 0)
        	throw new IllegalArgumentException("invalid count:" + count);
        if (offset > data.length - count)
            throw new ArrayIndexOutOfBoundsException(offset + count);
		ByteArrayOutputStream out = new ByteArrayOutputStream(data.length + data.length);
		PrintStream writer = new PrintStream(out);
		for (int i = offset; i < offset + count; i++) {
			writer.printf("%02x", data[i]);
		}
		return out.toString();
	}

	public static byte[] unhex(String hex) {
		char[] tb = hex.toUpperCase().toCharArray();
		List<Byte> bs = new ArrayList<Byte>();
		for (int i = 0; i < tb.length; i += 2) {
			String t = new String();
			t += tb[i];
			t += tb[i + 1];
			int safe = Integer.parseInt(t, 16);
			if (safe > 127)
				safe -= 256;
			bs.add(Byte.parseByte(safe + ""));
		}
		byte[] raw = new byte[bs.size()];
		for (int i = 0; i < bs.size(); i++)
			raw[i] = bs.get(i);
		return raw;
	}

}
